package cn.itcast.filter;


import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//@Order(-1)
@Component
public class AuthorFilter implements GlobalFilter, Ordered {

    /**
     * 过滤拦截
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        //0.exchange  包含request(获取请求参数)和response(响应数据)对象
//        ServerHttpRequest request = exchange.getRequest();
//        ServerHttpResponse response = exchange.getResponse();
//
//        //1.拦截用户请求，判断请求参数是否有  authorization,如果有，判断是否为admin
//        String authorization = request.getQueryParams().getFirst("authorization");
//        if(ObjectUtils.isEmpty(authorization) || !authorization.equals("admin")){
//            //2.如果不是admin,则拦截
//            //微服务网关输出信息
//            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            //指定编码，否则在浏览器中会中文乱码
//            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
//            return response.writeWith(Mono.just(response.bufferFactory().wrap("请先登录！".getBytes(StandardCharsets.UTF_8))));
//        }

        //3.是，就放行
        return chain.filter(exchange);
    }

    /***
     * 返回结果越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
